/********************************************************************
  V A R S
*******************************************************************/
var titleColor = null;
var initDataProcessed = 0;
var linksConfig = null;
var openTripKey = null;
var openHotelKey = null;
var openAreaKey = null;
var titleColor = "";
var activeColor = "";
var activeBgColor = "";
var hoverColor = "";
var hoverBgColor = "";
var linksCounter = 0;
var searchLinksCounter = 0;
var defaultText = "";
for(i=0;i<10;i++) {
	defaultText += "&nbsp;"
}


/********************************************************************
 J Q U E R Y    R E A D Y 
*******************************************************************/
$().ready(function() {

	/********* G E N E R A L *********************/
	linksConfig = getLinkConfig();
	//
	// setting the title color to the color of buttons instead of text
	titleColor = $(".ui-state-default").css("color");	
	activeColor = $(".ui-state-active").css("color");	
	activeBgColor = $(".ui-state-active").css("background-color");	
	hoverColor = $(".ui-state-hover").css("color");	
	hoverBgColor = $(".ui-state-hover").css("background-color");	

	// loading external HTML files
	loadingExternal();
		
	/**************** S P L I T T E R *********************/
	$("#splitterContainer").splitter({
		minAsize:300,
		maxAsize:800,
		splitVertical:true,
		A:$('#leftPane'),
		B:$('#rightPane'),
		closeableto:0});
	$(".leftPane").css("color", titleColor);	
	$(".title").css("color", titleColor);	
	$("button,a.button", "").button();


	/**************** C O N F I R M    D I A L O G *********************/
	$( "#dialog-confirm" ).dialog({
		autoOpen: false,
		resizable: false,
		height:160,
		modal: true,
		buttons: {
			"Delete": function() {
				if ($( "#dialog-confirm" ).attr("hotelKey") != null) {
					var hotelKey = $( "#dialog-confirm" ).attr("hotelKey");
					var hotelObj = jQuery.container(hotelKey);
					submitJsonRest(hotelObj, "hotel", "delete", function(data) {
						var deleteRowData = getHotelRowData(hotelObj.hotelInfo);
						deleteRowData.table.fnDeleteRow(deleteRowData.index);
						jQuery.container(hotelKey, null);

					});
					$( "#dialog-confirm" ).removeAttr("hotelKey")
					$( this ).dialog( "close" );						
				} else if ($( "#dialog-confirm" ).attr("areaKey") != null) {
					var areaKey = $( "#dialog-confirm" ).attr("areaKey");
					var area = jQuery.container(areaKey);
					submitJsonRest(area, "area", "delete", function(data) {
						$( "#areaDiv" + areaKey ).remove();
						jQuery.container(areaKey, null);
					});
					$( "#dialog-confirm" ).removeAttr("areaKey")
					$( this ).dialog( "close" );						
				} else if ($( "#dialog-confirm" ).attr("tripKey") != null) {
					var tripKey = $( "#dialog-confirm" ).attr("tripKey");
					$( "#dialog-confirm" ).removeAttr("tripKey")
					$( this ).dialog( "close" );						
					var trip = jQuery.container(tripKey);
					submitJsonRest(trip, "trip", "delete", function(data) {
						setTripKey(null);
						jQuery.container(data.key, null);
						$(  "#deleteTrip"  ).button({ disabled: true });
						$("#key").find("option:selected").remove();

						removeContent();
						$("#tripArea").hide();
					});
				}
			},
			Cancel: function() {
				$( this ).dialog( "close" );
			}
		}
	});

	/*************** H O T E L   D I A L O G S ********************/
	$( "#dialog-notice-form" ).dialog({
		autoOpen: false,
		height: 500,
		width: 300,
		modal: true,
		buttons: {
			"Submit": function() {
				var hotelKey = $("#notice_hotelKey").val();
				var formAction = ($("#notice_key").val() == "") ? "create" : "update";
				var hotelObj = jQuery.container(hotelKey);
				if (formAction != "create") {
					var reservation = hotelObj.reservation;	
				} else {
					var reservation = {
						hotelKey : hotelKey
					};
				}
				// updating from form
				reservation.startDate = $("#notice_startDate").val();
				reservation.endDate = $("#notice_endDate").val();
				reservation.cancellationDate = $("#notice_cancellationDate").val();
				reservation.emailReminderDate = $("#notice_emailReminderDate").val();
				reservation.emailReminder= ($("#notice_emailReminder").attr('checked') == null) ? false :true;
				reservation.email= $("#notice_email").val();
				reservation.reservationConfigKey= $("#notice_reservationConfigKey").val();
				reservation.infoLink = $("#notice_infoLink").val();
				reservation.cancellationLink = $("#notice_cancellationLink").val();
				
				submitJsonRest(reservation, "reservation", formAction, function(data) {
					jQuery.container(hotelKey).reservation = data;	
					var hotelObj = jQuery.container(hotelKey).hotelInfo;
					var rowData = getHotelRowData(hotelObj);
					rowData.table.fnUpdate( rowData.data , rowData.index, 0 );
				});
				$( this ).dialog( "close" );
			},
			"Delete": function() {
				var hotelKey = $("#notice_hotelKey").val();
				if ($("#notice_key").val() == ""){
					$( this ).dialog( "close" );
				} else {
					var reservation = {
						key : $("#notice_key").val(), 
						hotelKey : hotelKey
					};
					submitJsonRest(reservation, "reservation", "delete", function(data) {
						jQuery.container(hotelKey).reservation = null;	
						var hotelObj = jQuery.container(hotelKey).hotelInfo;
						var rowData = getHotelRowData(hotelObj);
						rowData.table.fnUpdate( rowData.data , rowData.index, 0 );
					});
					$( this ).dialog( "close" );
				}
			},
			Cancel: function() {
				$( this ).dialog( "close" );
			}
		}
	});


	/********* T R I P  *********************/
	initTrips();
	
	/************* H O T E L S    T A B L E *****************/
	$("a.hotel-row-ui-icon").live("click", function(){  
		var elem = $(this);
		var icon = elem.attr("icon");
		var hotelKey 	= elem.attr("hotel");
		var hotelObj	= jQuery.container(hotelKey);
		if (icon == "flag" || icon == "check") {
			var isDisabled 	= elem.hasClass("ui-state-disabled");
			var iconVal		= (isDisabled) ? true : false;
			if(icon == "flag") {
				hotelObj.hotelInfo.flagged = iconVal;
			} else if (icon == "check") {
				hotelObj.hotelInfo.booked = iconVal;
			}
			submitJsonRest(hotelObj, "hotel", "update", function(data) {
				elem.toggleClass("ui-state-disabled");
			});
		}
		if (icon == "pencil") {
			var areaKey = elem.attr("area");
			var areaObj	= jQuery.container(areaKey);
			openSearch(hotelObj, areaObj);
		}
		if (icon == "close") {
			$( "#dialog-confirm" ).attr("hotelKey", hotelKey);
			$( "#dialog-confirm" ).dialog( "open" );			
	
		}
		if (icon == "comment") {
			var comment	= (hotelObj.comment == null) ? "" :  hotelObj.comment;
			$( "#dialog-comments-form" ).attr("hotelKey", hotelKey);
			$( "#dialog-comments-form" ).dialog( "open" );
			$("#commentText").val(hotelObj.hotelInfo.comment);
		}
		if (icon == "notice") {
			$("#dialog-notice-form" ).dialog( "open" );
			$("#hotelReservationKey").val(hotelObj.key);
			if (hotelObj.reservation == null) {
				$("#notice_hotelKey").val(hotelKey);
				$("#notice_email").val(jQuery.container("email"));
				$("#notice_startDate").val($("#datepickerStart"+hotelObj.areaKey).val());
				$("#notice_endDate").val($("#datepickerEnd"+hotelObj.areaKey).val());
				$("#notice_infoOpen").button({ disabled: true});
				$("#notice_cancellationOpen").button({ disabled: true });
			} else {
				// add fields to the form
				for (var key in hotelObj.reservation) {
					$("#notice_"+key).val(hotelObj.reservation[key]);
				}
				if (hotelObj.reservation.emailReminder) {
					$("#notice_emailReminder").attr("checked", true);
				}
				$("#notice_infoOpen").button({ disabled: (hotelObj.reservation.infoLink == "") });
				$("#notice_cancellationOpen").button({ disabled: (hotelObj.reservation.cancellationLink == "") });
			}
		}

	});

	   
	$( "#dialog-comments-form" ).dialog({
			autoOpen: false,
			height: 260,
			width: 260,
			modal: true,
			buttons: {
				"Submit": function() {
					var hotelKey = $(this).attr("hotelKey");
					var commentStr = $("#commentText").val();
					var hotelObj = jQuery.container(hotelKey);
					hotelObj.hotelInfo.comment = commentStr;
					submitJsonRest(hotelObj, "hotel", "update", function(data) {
						var oTable = $("#hotelTable"+hotelObj.hotelInfo.areaKey).dataTable();
						var rowData = getHotelRowData(hotelObj.hotelInfo);
						oTable.fnUpdate( hotelObj.hotelInfo.comment , rowData.index, 7 );
					});
					$( this ).dialog( "close" );
				},
				Cancel: function() {
					$( this ).dialog( "close" );
				}
			}
		});




});

var preloading = new Array();
preloading[preloading.length] = "tripHtml";
preloading[preloading.length] = "areaHtml";
preloading[preloading.length] = "userData";
preloading[preloading.length] = "noticeDialog";
function processPreloading() {
		initDataProcessed++;
		if (initDataProcessed == preloading.length) {
			initTripData(openTripKey);
			$("#topTable").show();	
		}
}
function setTripKey(key) {
	openTripKey = key;
	jQuery.cookie('openTripKey',null);
	if(key != null) {
		jQuery.cookie('openTripKey',key, {expires: '7', path: '/'});
	}
}
function initTrips() {
	openTripKey = jQuery.cookie('openTripKey');
	submitJsonRest(null, "trip", "get", function(data) {
 		$.each(data, function(key, val) {
			jQuery.container(val.key, val);
			$('#key')
        	  	.append($('<option>', { value : val.key })
          		.text(val.name)); 
	  	});
		processPreloading();
	});
}
function initTripData(key){
	$(  "#deleteTrip"  ).button({ disabled: (key == null) });
	if (key == null) {
		$("#tripArea").hide();
		removeContent();
		return;
	}
	// setting the trip in select box and opening it
	if (key != null) {
		$("#key").val(key);
		if ($("#key").find("option:selected").index()> 0) {
			$("#tripKey").attr("value", key);
			var trip = {key: key}
			submitJsonRest(trip, "trip", "get", function(data) {
				// removing previous trip areas and showing the trip
				$("#areaPlaceHolder").empty();
				$("#tripArea").show()
				$("#title").empty();
				$("#title").append("Trip: " + data.trip.name);
				 $.each(data.areas, function(key,val){
					 doArea(val);
		    		});
			});
			$(  "#deleteTrip"  ).button({ disabled: false });
			return;
		}
	}
}

function getHotelLinksHtml(hotel) {
	var returnStr="";
	if (hotel.links != null) {
		for (i=0;i<hotel.links.length;i++) {
			hotelLink = hotel.links[i];
			if (hotelLink.link != "") {
				var linkConfig = getLinkConfig()[hotelLink.linkConfigKey];
				hotelLink.configName = linkConfig.name; 
				returnStr += '<a id="'+hotelLink.key+'" href="#" onClick="openHotelLink(this)" hotelKey="'+hotel.key+'" hotelLink="'+hotelLink.link+'" area="'+hotel.areaKey+'" linkConfigKey="'+linkConfig.key+'"><img title="'+linkConfig.name+'" alt="'+linkConfig.name+'" class="img_icon" src="'+linkConfig.iconPath+'"/></a>';
			}
		}
	}
	return returnStr;
}

function getIconButtonHtml(iconName, hotelObj, title, state, txt) {
	var buttonId = "hotel"+iconName+hotelObj.key;
	var returnStr = '<div class="ui-state-default ui-corner-all">';
	returnStr += '<table><tr><td><a class="hotel-row-ui-icon ui-icon ';
	if (state == null || state == false) {
		returnStr += "ui-state-disabled ";
	}
	returnStr += 'ui-icon-'+iconName+'" title="'+title+'" alt="'+title+'" icon="'+iconName+'" area="'+hotelObj.areaKey+'" hotel="'+hotelObj.key+'" id="'+buttonId+'">';
	returnStr += '</a></td><td>';
	if (txt != null) {
		returnStr += "</td><td><a href='#' class='hotel-row-ui-icon' ";
		returnStr += ' title="'+title+'" alt="'+title+'" icon="'+iconName+'" area="'+hotelObj.areaKey+'" hotel="'+hotelObj.key+'" id="'+buttonId+'">';
		returnStr += txt + "</a>";
	}
	returnStr += '</td></tr></table></div>';
	return returnStr;
}

function openHotelLink(hrefObj) {
	removeContent();

	var currentLink = $("#"+hrefObj.id);
	var area = jQuery.container(currentLink.attr("area"));
	var clickLinkConfig = currentLink.attr("linkConfigKey");
	var hotel = jQuery.container(currentLink.attr("hotelKey"));

	var hotelLinkHtml = new EJS({url: '/templates/hotelLinks.ejs'}).render(hotel);
	$("#openLinkDiv").html(hotelLinkHtml);
	$("#openLinkDiv").show();
	$("#hotelLinksTabs").tabs();

	var openLinkIndex = 0;
	var i=0;
	for (i=0;i< hotel.links.length;i++) {
		var link = hotel.links[i];
		var linkURL = checkLink(link.link);
		if (clickLinkConfig == link.linkConfigKey) {
			openLinkIndex = i;
		}
		var dateFormatStr = getLinkConfig()[link.linkConfigKey].forwardDateFormat;
		linkURL = setDateForHotelLink(linkURL, dateFormatStr, area);
		$("#hotelLinkHolder-" + link.key).empty();
		var linkObj = {openLink : linkURL, closeButton: false};

		var linkHtml = new EJS({url: '/templates/openLink.ejs'}).render(linkObj);
		$("#hotelLinkHolder-" + link.key).html(linkHtml);
	}
	$("#hotelLinksTabs").tabs('select',openLinkIndex);
	$( "button.openLink" ).button()
		.click(function() {
			window.open($(this).attr("href"), '_blank', '');
		});

	$( "button.closeLink" ).button()
	.click(function() {
		removeContent();
		$(".hotelLinkHolder").empty();
		return false;
	});
	return false;
}

function doHotels(area) {
	// getting the hotels for the area
	submitJsonRest({}, "hotel", "get", function(data) {
		$.each(data, function(key,val){
			jQuery.container(val.key, val);
			addHotel(val);
		});
	}, function (submitUrl) {
		return submitUrl + "?area="+area.key;
	});

}
function getHotelRowData(hotelInfo) {
	var hotelRowData = new Object();
	var hotelDataTable = $("#hotelTable"+hotelInfo.areaKey);
	var rows = hotelDataTable.dataTable().fnGetNodes(); 
	for (i=0;i<rows.length;i++) {
		var aData = hotelDataTable.dataTable().fnGetData(rows[i]);
		if (aData[0] == hotelInfo.key) {
			hotelRowData.index =i;
			hotelRowData.row = rows[i];
			hotelRowData.data = aData;
			hotelRowData.table = hotelDataTable;
			return hotelRowData;
		}
	}
	return hotelRowData;
}
function addHotel(val, action) {
	var hotelDataTable = $("#hotelTable"+val.hotelInfo.areaKey);
	hotelDataTable.show();
	if (val.hotelInfo.flagged == null) val.hotelInfo.flagged = false;
	if (val.hotelInfo.booked == null) val.hotelInfo.booked = false;
	if (action != null) {
		if (action == "update") {
			var deleteRowData = getHotelRowData(val.hotelInfo);
			hotelDataTable.dataTable().fnDeleteRow(deleteRowData.index);
		}
	}
	var rowData  =  [val.key, val.hotelInfo.flagged,val.hotelInfo.price,val.hotelInfo.name,"",val.hotelInfo.booked,val.hotelInfo.comment,"",""];

	// adding row through datatable API
	hotelDataTable.dataTable().fnAddData(rowData);
	$('td.editableTd').editable(function(value, settings) { 
		var areaKey = this.parentNode.getAttribute('area');
		var hotelKey = this.parentNode.getAttribute('id');
		var hotelObj = jQuery.container(hotelKey);
		var oTable = $("#hotelTable"+areaKey).dataTable();
		var aPos = oTable.fnGetPosition( this );
		var colPosition = aPos[2];
		switch (colPosition) {
			case 2:
				hotelObj.hotelInfo.price = value;
				break;
			case 3:
				hotelObj.hotelInfo.name = value;
				break;
		}
		submitJsonRest(hotelObj, "hotel", "update", function(data) {
			oTable.fnUpdate( value , aPos[0], aPos[2] );
		});
	     	return value;
	  }, { 
		"placeholder":"---" 
	 });
}

function openLink(linkURL) {
	linkURL = checkLink(linkURL);

	var linkObj = {openLink : linkURL, closeButton: true};
	var linkHtml = new EJS({url: '/templates/openLink.ejs'}).render(linkObj);
	$("#openLinkDiv").html(linkHtml);
	$( "#close", "" ).button(); 
	$( "#close" ).button()
		.click(function() {
			removeContent();
			$("#openLinkDiv").empty();
			return false;
		});
	$( "button.openLink", "" ).button(); 
	$( "button.openLink" ).button()
		.click(function() {
			window.open(linkURL, '_blank', '');
		});
	$( "button.closeLink" ).button()
	.click(function() {
		removeContent();
		return false;
	});
	removeContent();
	$("#openLinkDiv").show();
	return false;
}



$( "button.addHotel", "" ).live("click", function() { 
	var openAreaKey = $(this).attr("area");
	openSearch({}, jQuery.container(openAreaKey));
});
$( "button.deleteArea", "" ).live("click",function() { 
	var areaKey = $(this).attr("area");
	$( "#dialog-confirm" ).attr("areaKey", areaKey);
	$( "#dialog-confirm" ).dialog( "open" );
});
function doArea(val, action) {
	jQuery.container(val.key, val);
	var areaHtml = new EJS({url: '/templates/area.ejs'}).render(val);
	$("#areaPlaceHolder").append(areaHtml);
	$( "input:submit, a.deleteArea, a.addHotel, button", "" ).button();
	/*
	$( "button.deleteArea", "" ).click(function() { 
		var areaKey = $(this).attr("area");
		$( "#dialog-confirm" ).attr("areaKey", areaKey);
		$( "#dialog-confirm" ).dialog( "open" );
	});
	$( "button.addHotel", "" ).click(function() { 
		var openAreaKey = $(this).attr("area");
		openSearch({}, jQuery.container(openAreaKey));
	});
	*/
	$("font.editArea"+val.key).editInPlace({
		bg_over: hoverColor,
		callback : function(unused, enteredText) {
			var areaKey = $(this).attr("area");
			var fieldName =$(this).attr("fieldName");
			if (areaKey != null && areaKey != "") {
				var areaObj = jQuery.container(areaKey);
				areaObj[fieldName] = enteredText;
				submitJsonRest(areaObj, "area", "update");
				return enteredText;
			}
		},
		show_buttons : false
	});
	$("#datepickerStart"+val.key).datepicker(
		{ 
			dateFormat: 'dd/mm/yy' ,
			onClose: function(dateText, inst) { 
				var areaKey = $( "#" + inst.id ).attr("area");
				var area = jQuery.container(areaKey);
				area.startDate =  dateText;
				submitJsonRest(area, "area", "update");
	}
		}
	);
	$("#datepickerEnd"+val.key).datepicker(
		{ 
			dateFormat: 'dd/mm/yy' ,
			onClose: function(dateText, inst) { 
				var areaKey = $( "#" + inst.id ).attr("area");
				var area = jQuery.container(areaKey);
				area.endDate =  dateText;
				submitJsonRest(area, "area", "update");
			}
		}
	);

	$("#hotelTable"+val.key).dataTable( {
		"aoColumns": [ 
		{ "bVisible": false },
			{
				"fnRender": function ( oObj ) {
					var hotelObj = jQuery.container(oObj.aData[0]);
					return getIconButtonHtml("flag", hotelObj.hotelInfo, "flag", hotelObj.hotelInfo.flagged);
				}
				
			},
			{ "bSortable": true, "sClass":"editableTd" },
			{ "bSortable": true, "sClass":"editableTd" },
			{ 
				"fnRender": function ( oObj ) {
					var hotelObj = jQuery.container(oObj.aData[0]);
					return getHotelLinksHtml(hotelObj);
				} ,"bSortable": false 
			},
			{
				"fnRender": function ( oObj ) {
					var hotelObj = jQuery.container(oObj.aData[0]);
					return getIconButtonHtml("notice", hotelObj.hotelInfo, "reservation", (hotelObj.reservation != null));
				}
			},
			{
				"fnRender": function ( oObj ) {
					var hotelObj = jQuery.container(oObj.aData[0]);
					return getIconButtonHtml("check", hotelObj.hotelInfo, "booked", hotelObj.hotelInfo.booked);
				}
			},
			{ 
				"fnRender": function ( oObj ) {
					var hotelObj = jQuery.container(oObj.aData[0]).hotelInfo;
					var  showText = null;
					var iconText = null;
					if (hotelObj.comment != null && hotelObj.comment != "") {
						if (hotelObj.comment.length >=8) {
							showText = hotelObj.comment.substring(0,5) + "...";
						} else {
							showText = hotelObj.comment;
						}
						iconText = "comment: " + hotelObj.comment;
					} else {
						showText = null;
						iconText = "no comment";
					}
					return getIconButtonHtml("comment", hotelObj, iconText, (showText != null), showText);
				} ,"bSortable": false 
			},
			{
				"fnRender": function ( oObj ) {
					var hotelObj = jQuery.container(oObj.aData[0]);
					return getIconButtonHtml("pencil", hotelObj.hotelInfo, "edit", true);
				}, "bSortable":false, "sWidth":"20px"
			},
			{
				"fnRender": function ( oObj ) {
					var hotelObj = jQuery.container(oObj.aData[0]);
					return getIconButtonHtml("close", hotelObj.hotelInfo, "delete", true);
				}, "bSortable":false, "sWidth":"20px"
			}
		
		],
	       "aaSorting": [[ 3, "asc" ]],
       		"bPaginate": false,
  		"bLengthChange": false,
      		"bFilter": true,
       		"bSort": true,
       		"bInfo": false,
       		"bAutoWidth": true,
		"bJQueryUI": true,
		"fnRowCallback": function( nRow, aData, iDisplayIndex ) {
			nRow.setAttribute("id", aData[0]);
			nRow.setAttribute("area", val.key);
			return nRow;
		}
		
	});
	if (action == null) {
		doHotels(val);
	}
	setToggle(val.key);

	$(".title").css("color", titleColor);	
}
/*************** H O T E L   S E A R C H *************************/

function openSearch(hotel, area) {
	
	removeContent();
	var combinedDetails = {
		hotel : hotel,
		area : area,
		links: linksConfig
	}
	var searchHtml = new EJS({url: '/templates/searchHotel.ejs'}).render(combinedDetails);
	$("#searchHotelDiv").html(searchHtml);
	$( "#closeSearch", "" ).button(); 
	$( "#closeSearch" ).button()
		.click(function() {
			$("#searchHotelDiv").empty();
			removeContent();
			return false;
		});
	
	$( "#hoteltabs" ).tabs();	
	$( "#hoteltabs" ).show();	
	if (hotel) {
		if (hotel.links) {
			for (i=0;i<hotel.links.length;i++) {
				linkInput = $("#openLink_"+hotel.links[i].linkConfigKey);
				linkInput.val(hotel.links[i].link);
			}
		}
	}
	$( "button,a.openUrl", "").button();
	$( "#doSearch" ).button()
	.click(function() {
		for (var i in linksConfig) {
			window["LinksFrame_" + linksConfig[i].counter].executeSearch(getSearchText());	
		}
		return false;
	});
	$( "#submitSearchHotelForm" ).button()
	.click(function() {
		var action =  (hotel.hotelInfo != null) ? "update" : "create";
		if (action == "create") {
			hotel = {hotelInfo : {
				key : null
			}}; 
		}
		var linksArr = new Array();
		for (var i in linksConfig) {
			var linkVal = $("#openLink_"+i).val();
			if (linkVal != "") {
				linksArr[linksArr.length] = { 
					linkConfigKey : i,
					hotelKey : hotel.hotelInfo.key,
					link : $("#openLink_"+i).val()
				};
			}
		}
		hotel.hotelInfo.areaKey = $("#searchAreaKey").val();
		hotel.hotelInfo.name = $("#searchHotelName").val();
		hotel.links = linksArr;
		submitJsonRest(hotel, "hotel", action, function(data) {
			addHotel(data, action);		
			removeContent();
		});	
		return false;
	});
	$("#searchHotelDiv").show();
	return false;
}

function searchPageInitialized(linkData) {
	searchLinksCounter--;
	if (searchLinksCounter==0) {
		$( "#searchHotelName" ).removeAttr("disabled");
		$(  "#doSearch"  ).button({ disabled: false });
		searchLinksCounter = linksCounter;
	}

}

function setHotelUrlLinkForForm(linkKey, hotelUrl) {
	$( "#openLink_" + linkKey).val(hotelUrl);
	return;
}

function getSearchText() {
	var hotelName = $("#searchHotelName").attr("value");
	if (hotelName != null && hotelName != "") {
		return hotelName + " " + $("#searchHotelCity").attr("value");
	} else {
		return;
	}
}

function removeContent() {
	$(".contentDiv").hide();
	//$("#blankDiv").show();
}

function checkLink(linkURL){
	if ( linkURL.indexOf("http") < 0) {
		linkURL = "http://" + linkURL;
	}
	return linkURL;
}
function setDateForHotelLink(linkURL, dateFormatStr, area) {
	if (dateFormatStr != null) {
		var startDate = area.startDate;
		var endDate = area.endDate;

		var isWithDate = false;
		if (startDate != null && startDate != "") {
			isWithDate = true;
			splitDate = startDate.split("/");
			dateFormatStr = dateFormatStr.replace("STARTDATE_YYYY", splitDate[2]);
			dateFormatStr = dateFormatStr.replace("STARTDATE_D", splitDate[0]);
			dateFormatStr = dateFormatStr.replace("STARTDATE_M", splitDate[1] );
		}	
		if (endDate != null && endDate != "") {
			isWithDate = true;
			splitDate = endDate.split("/");
			dateFormatStr = dateFormatStr.replace("ENDDATE_YYYY", splitDate[2]);
			dateFormatStr = dateFormatStr.replace("ENDDATE_D", splitDate[0]);
			dateFormatStr = dateFormatStr.replace("ENDDATE_M", splitDate[1] );
		}	

		if (isWithDate) {
			linkURL += dateFormatStr;
		}
	}
	return linkURL;

}

function loadingExternal() {
	/******* L O A D I N G   A L L   E X T E R N A L    H T M L *************/
	$("#header").load('inner_header.html', function() {
		$( "#deleteTrip" )
			.button()
			.click(function() {
				$( "#dialog-confirm" ).attr("tripKey", openTripKey);
				$( "#dialog-confirm" ).dialog( "open" );
		});
		$(  "#deleteTrip"  ).button({ disabled: (openTripKey == null) });
		$('#key').change(function() {
			jQuery.cookie('openTripKey',null);
			if ($("#key").find("option:selected").index()> 0) {
				openTripKey = $("#key").val();
				jQuery.cookie('openTripKey',openTripKey, {expires: '7', path: '/'});
			} else {
				jQuery.cookie('openTripKey',null);
				openTripKey = null;
				$(  "#deleteTrip"  ).button({ disabled: true });
			}
			removeContent();
			initTripData(openTripKey);
		});
		$( "#addTrip" ).button().click(function() {
			if ($("#tripName").val() != "") {
				var trip = {name: $("#tripName").val()};
				submitJsonRest(trip, "trip", "create", function(data) {
					$('#key')
        				  .append($('<option>', { value : data.key })
          					.text(data.name)); 
					jQuery.container(data.key, data);
					setTripKey(data.key);
					initTripData(data.key);
				});
				$("#tripName").val("");
			}
		});

		// setting user related data
		submitJsonRest(null, "user", "get", function(data) {
			$("#logout").attr("logoutUrl",data.logoutUrl);
			$( "#logout" )
				.button()
				.click(function() {
				top.location.href=$("#logout").attr("logoutUrl");
			});
			$("#userName").append(data.userName + "'s Trips:");
			jQuery.container("email", data.email);
			processPreloading();
		});

		// setting the user settings
		$( "#settings" )
			.button()
			.click(function() {
				removeContent();
				$("#settingsDiv").show();
		});
		$("#settings"  ).button({ disabled:true });
		$("#settingsDiv").load('inner_settings.html', function() {
			$("#settings"  ).button({ disabled:false });
			$( "#SubmitSettings" )
			.button().click(function() {
				var themeValue = $('#changeLayoutTheme').val();
				jQuery.cookie('uitheme',null);
				jQuery.cookie('uitheme',themeValue, {expires: 7, path: '/'});
				top.frames.document.location.href = "/";
			});
			$('#changeLayoutTheme').val(theme);

		});
		processPreloading();
	});
	$("#tripArea").load('inner_area.html', function() {
		$( "#addArea" )
			.button()
			.click(function() {
				if ($("#city").val() != "") {
					var newArea = {
						tripKey: openTripKey,
						name: $("#area").val(),
						city: $("#city").val()
					};
					submitJsonRest(newArea, "area", "create", function(data) {
						$("#city").val("");
						$("#area").val("");
						doArea(data, "create");
					});	
				}
				return false;
		});
			
		setToggle("newArea");
		processPreloading();
	});
	$("#dialog-notice-form").load('inner_reservation_dialog.html', function() {
		
		for (var key in getLinkConfig()) {
			$('#notice_reservationConfigKey')
	       			.append($('<option>', { value : key })
	      		  		.text(getLinkConfig()[key].name)); 
		}
		$( "button.doOpenLink", "" ).click(function() { 
			var field = $(this).attr("field");
			var openLinkSrc = $("#notice_"+field+"Link").val();
			openLink(openLinkSrc);
			return false;
		});
	
		$("#notice_infoOpen").button({ disabled: true });
		$("#notice_cancellationOpen").button({ disabled: true });
		$( ".uiLink").change(function() {
			txt = $(this).val();
			field = $(this).attr("field");
			$("#notice_"+field+"Open").button({ disabled: (txt == "") });
		});	
		$(".datepickerNoticeForm").datepicker(
			{ 
				dateFormat: 'dd/mm/yy' ,
				onClose: function(dateText, inst) { 
				}
			}
		);
	
		processPreloading();
	});
}

/********************************************************************
  A J A X / J S O N
*******************************************************************/
$.ajaxSetup({
      "error":function(x) { alert("Error:" + x.responseText);  }
});
function submitJsonRest(obj, modelName,  action, callbackFunction, updateUrlFunction) {
	var inputJSON = null;
	var submitUrl = "/dispatch/"+modelName+"/"+action;
	if (this.document.location.href.indexOf("admin") > 0 ) {
		submitUrl = "/admin" + submitUrl;
	}
	if (obj) {
		if (action == "create" || action == "update") {
			inputJSON = $.toJSON(obj);
			//console.log("inputJSON:" + inputJSON);
		}
		if (obj.key) {
			submitUrl += "/"+obj.key;
			//console.log("submitURL:"+submitUrl);
		}
	}
	submitUrl += ".json";
	//console.log("submitURL:"+submitUrl);
	if (updateUrlFunction) {
		submitUrl= updateUrlFunction(submitUrl);
	}
	$.ajax({
  		type: 'POST',
  		url: submitUrl,
  		data: inputJSON,
  		success: function(data) {
			jQuery.container(data.key, data);
			if (callbackFunction) {
				callbackFunction(data);
			};
		},
  		dataType: 'json'
	});
	/*

	$.getJSON(submitUrl, inputJSON, function(data) {
		jQuery.container(data.key, data);
		if (callbackFunction) {
			callbackFunction(data);
		}
	});	
	*/
}
/********************************************************************
  G E N E R A L    U I    E L E M E N T S
*******************************************************************/
function setToggle(elemId) {
	$("#toggle"+elemId).attr("title", "toggle");
	$("#toggle"+elemId).click(function() {
		var toggleKey =$(this).attr("toggleDivId");
		$(this).toggleClass("ui-icon-circle-triangle-e");
		$(this).toggleClass("ui-icon-circle-triangle-s");
		$('#'+toggleKey).toggle('blind', {}, 200);
	})
}
/********************************************************************
  C O N F I G U R A T I O N    D A T A
*******************************************************************/
function getLinkConfig() {
	if (jQuery.container('linkConfig') == null) {
		$.ajaxSetup( { "async": false } );	
		jQuery.container('linkConfigTemp', new Array());
		$.getJSON('/dispatch/linkconfig/get.json', function(data) {
 			$.each(data, function(key, val) {
				val.counter = linksCounter++;
				if(val.forwardDateFormat) {
					val.forwardDateFormat = val.forwardDateFormat.replace(/&/gi, "%26");
				}
				jQuery.container('linkConfigTemp')[val.key] = val;
	  		});
			_linksLoading = jQuery.container('linkConfigTemp');
			jQuery.container('linkConfig', _linksLoading);
		});
		searchLinksCounter = linksCounter;
		$.ajaxSetup( { "async": true } );	
	}
	return  jQuery.container('linkConfig');
}

